<?php
namespace Admin\Controller;
use Think\Controller;
class OrderController extends CommonController {
    public function index(){
        //将电工未同意的就近安装过期订单改为默认抢单
        $time = strtotime("-24 hours");
        $back_time =  date("Y-m-d H:i:s",$time);
        $condition = array(
            'install_type'=>2,
            'electrician_confirm'=>array(
                'neq',1
            ),
            'add_time'=>array(
                'lt',$back_time
            )
        );
        $data['install_type'] = 1;
        $data['electrician_confirm'] = '';
        $data['electrician_id'] = 0;
        M('order')->where($condition)->save($data);

        //输入框搜索
        $search = I('search');
        if($search){
            $where['o.order_number'] = array('like',"%$search%");
            $where['u.username'] = array('like',"%$search%");
            $where['o.good_name'] = array('like',"%$search%");
            $where['_logic'] = 'OR';
        }

        //安装状态
        $install_status = I('install_status');
        if($install_status != ''){
            $map['install_status'] = $install_status;
            $map['is_install'] = 1;
        }

        //订单状态搜索
        $order_status = I('order_status');
        if($order_status != ''){
            $map['order_status'] = $order_status;
        }

        //尾款状态搜索
        $final_payment_status = I('final_payment_status');
        if($final_payment_status != ''){
            $map['final_payment_status'] = $final_payment_status;
        }

        if($where != ''){
            $map['_complex'] = $where;
        }

        //默认排序
        $order = 'order_id desc';

        //接受此参数，代表直接查询尾款订单
        $final_payment_order = I('final_payment_order');
        $time = strtotime("-1 year");
        $back_time =  date("Y-m-d 23:59:59",$time);
        if($final_payment_order == 1){
            $map['final_payment_status'] = 1;
            $map['install_time'] = array('elt',$back_time);
            $order = 'install_time';//如果是尾款订单按安装完成时间升序排列
        }

        $row = 6;
        $p = $_GET['p'] ? $_GET['p'] : 1;

        //先按订单编号去重查询有多少待处理的尾款订单
        $final_payment_order_count = M('order o')
            ->field('o.*,cp.order_price,cp.count_price,cp.adminuser_id,cp.time,cp.text,a.username as admin_name,u.username,e.username AS electrician_name,
            e.phone as electrician_phone,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('LEFT JOIN __COUNT_PRICE__ cp on cp.order_number = o.order_number')
            ->join('LEFT JOIN __ADMINISTRATOR__ a on a.id = cp.adminuser_id')
            ->join('__USER__ u on u.id = o.user_id')
            ->join('LEFT JOIN __USER__ e on e.id = o.electrician_id')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where(array('final_payment_status'=>1,'install_time'=>array('elt',$back_time)))
            ->count("distinct o.order_number");

        //先按订单编号去重查询有 多少订单
        $order_number_count = M('order o')
            ->field('o.*,cp.order_price,cp.count_price,cp.adminuser_id,cp.time,cp.text,a.username as admin_name,u.username,e.username AS electrician_name,
            e.phone as electrician_phone,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('LEFT JOIN __COUNT_PRICE__ cp on cp.order_number = o.order_number')
            ->join('LEFT JOIN __ADMINISTRATOR__ a on a.id = cp.adminuser_id')
            ->join('__USER__ u on u.id = o.user_id')
            ->join('LEFT JOIN __USER__ e on e.id = o.electrician_id')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($map)
            ->count("distinct o.order_number");
        $Page = new \Think\Page($order_number_count,$row);
        $show = $Page->show();

        //获取该用户的有哪些订单（订单编号去重查询）
        $order_number_list = M('order o')
            ->field('o.*,cp.tracking_number,cp.order_price,cp.count_price,cp.adminuser_id,cp.time,cp.text,a.username as admin_name,u.username,e.username AS electrician_name,
            e.phone as electrician_phone,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
            ->join('LEFT JOIN __COUNT_PRICE__ cp on cp.order_number = o.order_number')
            ->join('LEFT JOIN __ADMINISTRATOR__ a on a.id = cp.adminuser_id')
            ->join('__USER__ u on u.id = o.user_id')
            ->join('LEFT JOIN __USER__ e on e.id = o.electrician_id')
            ->join('JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
            ->join('JOIN __AREA__ pr ON pr.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tw ON tw.code = ua.town')
            ->where($map)->page($p,$row)->order($order)->group('o.order_number')->select();

        //查询系统配置信息.获取最低安装费，安装费返点临界值，安装费返点
        $configInfo = M('system_config')->where(array('config_id' => array('in','1,2')))->getField('config_name,config_value');

        //获取每个订单编号下的商品信息和商品数量
        foreach($order_number_list AS $k => $v){
            $total_freight = '';//总运费
            $good_total = '';//商品小计
            $total_install_price = '';//总安装费
            $con = array(
                'order_number' => $v['order_number'],
            );
            //商品数量
            $order_good_count = M('order')->where($con)->count();

            //对应商品
            $order_good_list = M('order')->where($con)->order('order_id desc')->select();

            //遍历商品信息获取总运费，总安装费、总额
            foreach($order_good_list AS $key => $val){
                $order_good_list[$key]['good_small_total'] = $val['price']*$val['num'];
                $total_freight += $val['freight'];
                $total_install_price += $val['install_price'];
                $good_total += $val['price']*$val['num'];
            }

            $order_number_list[$k]['order_good_count'] = $order_good_count;
            $order_number_list[$k]['order_good_list'] = $order_good_list;
            $order_number_list[$k]['total_freight'] = $total_freight;
            //判断总的安装费是否满足最低安装费，不满则按最低安装费计算,等于0代表不需要安装
            if($total_install_price < $configInfo['min_install_price']  && $total_install_price != 0){
                $total_install_price = $configInfo['min_install_price'];
                $order_number_list[$k]['total_install_price'] = $configInfo['min_install_price'];
            }else{
                $order_number_list[$k]['total_install_price'] = $total_install_price;
            }
            $order_number_list[$k]['total_install_price'] = $total_install_price;
            $order_number_list[$k]['total'] = $total_freight + $total_install_price + $good_total;//订单总额
        }

        $this->assign('p',$p);
        $this->assign('search',$search);
        $this->assign('opentype_check',$order_status);
        $this->assign('install_check',$install_status);
        $this->assign('final_payment_status_check',$final_payment_status);
        $this->assign('final_payment_order_count',$final_payment_order_count);
        $this->assign('page',$show);
        $this->assign('order_number_list',$order_number_list);
        $this->assign('configInfo',$configInfo);
        $this->display();
    }

    //取消订单
    public function order_cancel(){
        $order_status = I('order_status');
        $install_status = I('install_status');
        $final_payment_status = I('final_payment_status');
        $search = I('search');
        $p = I('p');
        $on = I('on');
        $data['order_status'] = -1;
        if(false == M('order')->where('order_number='.$on)->save($data)){
            $this->error('数据异常，请稍后重试',U('index',array('p'=>$p,'order_status'=>$order_status,'install_status'=>$install_status,'final_payment_status'=>$final_payment_status,'search'=>$search)));
        }
        $this->success('订单已取消',U('index',array('p'=>$p,'order_status'=>$order_status,'install_status'=>$install_status,'final_payment_status'=>$final_payment_status,'search'=>$search)));
    }

    //删除订单
    public function order_del(){
        $order_status = I('order_status');
        $install_status = I('install_status');
        $final_payment_status = I('final_payment_status');
        $search = I('search');
        $p = I('p');
        $on = I('on');
        $oc = I('oc');
        $data['order_status'] = -2;
        if($on != ''){
            if(false == M('order')->where('order_number='.$on)->save($data)) {
                $this->error('数据异常，请稍后重试', U('index', array('p' => $p, 'order_status' => $order_status, 'install_status' => $install_status)));
            }
        }else{
            if(false == M('order')->where('order_id='.$oc)->save($data)) {
                $this->error('数据异常，请稍后重试', U('index', array('p' => $p, 'order_status' => $order_status, 'install_status' => $install_status)));
            }
        }
        $this->success('订单已删除',U('index',array('p'=>$p,'order_status'=>$order_status,'install_status'=>$install_status,'final_payment_status'=>$final_payment_status,'search'=>$search)));
    }

    //编辑订单
    public function order_edit(){
        if(!IS_POST){
            $p = I('p');
            $order_status = I('order_status');
            $install_status = I('install_status');
            $final_payment_status = I('final_payment_status');
            $search = I('search');
            $info = M('count_price as cp')
                ->field('cp.*,a.username,o.order_status')
                ->join('LEFT JOIN __ADMINISTRATOR__ a on a.id = cp.adminuser_id')
                ->join('LEFT JOIN __ORDER__ o on o.order_number = cp.order_number')
                ->where(array('cp.order_number'=>I('order_number')))
                ->find();
            $this->assign('p',$p);
            $this->assign('search',$search);
            $this->assign('opentype_check',$order_status);
            $this->assign('install_check',$install_status);
            $this->assign('final_payment_status_check',$final_payment_status);
            $this->assign('info',$info);
            $this->display();
        }else{
            if(I('tracking_number')){
                $data['tracking_number'] = I('tracking_number');
            }

            //修改价格后会同步修改订单号，以便进行微信扫码支付
            if(I('count_price') != I('order_price') && I('old_count_price') != I('count_price')){
                $data['count_price'] = I('count_price');
                $data['adminuser_id'] = session('uid');
                $data['time'] = date('Y-m-d H:i:s');
                $data['order_number'] = time().mt_rand(1000,9999);
                //修改订单表中的订单号
                if(false === M('order')->where(array('order_number'=>I('order_number')))->save(array('order_number'=>$data['order_number']))){
                    $this->error('订单修改失败');
                }
            }

            if(I('text')){
                $data['text'] = I('text');
            }
            //开启事务
            if(false === M('count_price')->where('order_number='.I('order_number'))->save($data)){
                $this->error('数据异常，请稍后重试',U('index',array('p'=>I('p'))));
            }
            $this->success('操作成功',U('index',array('p'=>I('p'),'order_status'=>I('order_status_check'),'install_status'=>I('install_status_check'),'final_payment_status'=>I('final_payment_status_check'),'search'=>I('search'))));
        }
    }
    
    //发货
    public function delivery()
    {
        $p = I('p');
        $order_status = I('order_status');
        $install_status = I('install_status');
        $final_payment_status = I('final_payment_status');
        $search = I('search');
        $data = array(
            'order_status' => 2,
            'delivery_time' => date('Y-m-d H:i:s'),
        );
        $deliveryResult = M('order')->where(array('order_number' => I('on')))->save($data);
        if($deliveryResult === false){
            $this->error('发货失败',U('index',array('p'=>$p,'order_status'=>$order_status,'install_status'=>$install_status)));
        }else{
            $this->success('发货成功',U('index',array('p'=>$p,'order_status'=>$order_status,'install_status'=>$install_status,'final_payment_status'=>$final_payment_status,'search'=>$search)));
        }
    }

    //确认收货
    public function confirm_receive()
    {
        $p = I('p');
        $order_status = I('order_status');
        $install_status = I('install_status');
        $final_payment_status = I('final_payment_status');
        $search = I('search');
        $data = array(
            'order_status' => 3,
            'confirm_time' => date('Y-m-d H:i:s'),
        );
        $deliveryResult = M('order')->where(array('order_number' => I('on')))->save($data);
        if($deliveryResult === false){
            $this->error('收货失败',U('index',array('p' => $p,'order_status'=>$order_status,'install_status'=>$install_status)));
        }else{
            $this->success('收货成功',U('index',array('p' => $p,'order_status'=>$order_status,'install_status'=>$install_status,'final_payment_status'=>$final_payment_status,'search'=>$search)));
        }
    }

    //查看换货信息和用户的点击已换货
    public function order_return_info()
    {
        if(!IS_POST)
        {
            $id = I('oc');
            $p = I('p');
            $order_status = I('order_status');
            $install_status = I('install_status');
            $final_payment_status = I('final_payment_status');
            $search = I('search');
            $where['order_id'] = $id;
            //查询退换货订单信息
            $orderInfo = M('order')
                ->field('o.*,ua.*,pr.name AS province,ci.name AS city,co.name AS county,tw.name AS town')
                ->join('AS o JOIN __USER_ADDRESS__ AS ua ON o.address_id = ua.address_id')
                ->join('JOIN __AREA__ pr ON pr.code = ua.province')
                ->join('JOIN __AREA__ ci ON ci.code = ua.city')
                ->join('JOIN __AREA__ co ON co.code = ua.county')
                ->join('JOIN __AREA__ tw ON tw.code = ua.town')
                ->where($where)
                ->find();
            //将订单中换货由JSON格式转化为数组
            $orderInfo['return_picture'] = json_decode($orderInfo['return_picture'],true);
            $this->assign('p',$p);
            $this->assign('order_status',$order_status);
            $this->assign('install_status',$install_status);
            $this->assign('final_payment_status',$final_payment_status);
            $this->assign('install_status',$install_status);
            $this->assign('search',$search);
            $this->display();
            exit;
        }else{
            $p = I('p');
            $order_status = I('order_status_check');
            $install_status = I('install_status_check');
            $final_payment_status = I('final_payment_status_check');
            $search = I('search');
            $data['order_id'] = I('order_id');
            $data['order_status'] = I('orderStatus');
            $data['confirm_return_time'] = date('Y-m-d H:i:s');
            M('order')->save($data);
            if(false === M('order')->save($data)){
                $this->error('数据异常，请稍后重试',U('index',array('p' => $p,'order_status'=>$order_status,'install_status'=>$install_status)));
            }
            $this->success('提交成功',U('index',array('p' => $p,'order_status'=>$order_status,'install_status'=>$install_status,'final_payment_status'=>$final_payment_status,'search'=>$search)));
        }
    }
}